﻿using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;


namespace ManageData
{
    internal class 使用外部事务
    {
        void MyMethod()
        {
            using (var connection = new SqlConnection(""))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var command = connection.CreateCommand();
                        command.Transaction = transaction;
                        command.CommandText = "select * from TableName";
                        command.ExecuteNonQuery();
                        var options = new DbContextOptionsBuilder<BasicDbContext>().UseSqlServer(connection).Options;

                        using (var db = new BasicDbContext(options))
                        {
                            db.Database.UseTransaction(transaction);
                            // 业务代码
                            db.SaveChanges();
                        }
                        transaction.Commit();
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }

        }

    }
}
